//
//  YSGMyopiaRecordController.swift
//  EyeVisionForPatients
//
//  Created by PMC on 2021/1/5.
//  Copyright © 2021 QDSG. All rights reserved.
//

import UIKit
import IQKeyboardManagerSwift

/// 检查记录
class YSGMyopiaRecordController: BaseViewController {
    
    private var viewModel: YSGMyopiaRecordDetailViewModel? {
        didSet {
            guard let vm = viewModel else { return }
            
            bottomView.isHidden = false
            tableView.reloadData()
            
            updateBottomViewLayout(vm.canSave)
        }
    }
    
    private var buttonViewHeight: CGFloat = 0
    
    let recordId: String
    
    init(recordId: String) {
        self.recordId = recordId
        super.init(nibName: nil, bundle: nil)
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()

        title = "检查记录"
        buttonViewHeight = buttonViewHContraint.constant
        loadData()
    }
    
    @IBOutlet private weak var buttonViewHContraint: NSLayoutConstraint!
    
    @IBOutlet private weak var bottomView: UIView! {
        didSet {
            bottomView.isHidden = true
        }
    }
    
    @IBOutlet private weak var saveCheckBtn: UIButton! {
        didSet {
            saveCheckBtn.layer.borderWidth = 1
            saveCheckBtn.layer.borderColor = UIColor.mainColor.cgColor
            saveCheckBtn.layer.cornerRadius = saveCheckBtn.height / 2
            saveCheckBtn.setShadow(color: .main, radius: 2)
        }
    }
    
    @IBOutlet private weak var advisoryBtn: UIButton! {
        didSet {
            advisoryBtn.layer.cornerRadius = advisoryBtn.height / 2
            advisoryBtn.setShadow(color: .main, radius: 2)
        }
    }

    @IBOutlet private weak var tableView: UITableView! {
        didSet {
            tableView.separatorStyle = .none
            tableView.backgroundColor = .background
            tableView.tableFooterView = UIView()
            tableView.estimatedRowHeight = 190
            tableView.rowHeight = UITableView.automaticDimension
            
            tableView.register(YSGMyopiaRecordInfoCell.nibForCell(),
                               forCellReuseIdentifier: YSGMyopiaRecordInfoCell.reuseIdentifier())
            tableView.register(YSGMyopiaRecordImageCell.nibForCell(),
                               forCellReuseIdentifier: YSGMyopiaRecordImageCell.reuseIdentifier())
            tableView.register(YSGMyopiaRecordEyePressureCell.nibForCell(),
                               forCellReuseIdentifier: YSGMyopiaRecordEyePressureCell.reuseIdentifier())
            tableView.register(YSGMyopiaEyeDegreeCell.nibForCell(),
                               forCellReuseIdentifier: YSGMyopiaEyeDegreeCell.reuseIdentifier())
            tableView.register(YSGMyopiaEyeVisionCell.nibForCell(),
                               forCellReuseIdentifier: YSGMyopiaEyeVisionCell.reuseIdentifier())
        }
    }
    
    @IBAction private func advisoryAction() {
        let doctorReserve = DoctorReserveController(with: .advisory, recordId: recordId, fromMyopia: true)
        navigationController?.pushViewController(doctorReserve, animated: true)
    }
    
    @IBAction private func saveCheckInfo() {
        submitEditedCheckInfo()
    }
    
    private func updateBottomViewLayout(_ canSave: Bool?) {
        if canSave == false {
            if buttonViewHContraint.constant == buttonViewHeight - 60 {
                return
            }
            saveCheckBtn.isHidden = true
            buttonViewHContraint.constant -= 60
            UIView.animate(withDuration: 0.25) {
                self.view.layoutIfNeeded()
            }
        } else {
            saveCheckBtn.isHidden = false
            buttonViewHContraint.constant = buttonViewHeight
            UIView.animate(withDuration: 0.25) {
                self.view.layoutIfNeeded()
            }
        }
    }
    
    private func loadData() {
        HUDTool.showActivity()
        YSGMyopiaRecordViewModel.getMyopiaRecordDetail(recordId: recordId) { (model, message, code)  in
            HUDTool.hideActivity()
            switch code {
            case .failure:
                HUDTool.showError(message: message)
            case .success:
                if let model = model {
                    var viewModel = YSGMyopiaRecordDetailViewModel(model: model)
                    viewModel.setCheckInfoArr()
                    self.viewModel = viewModel
                }
            }
        }
    }
    
    private func submitEditedCheckInfo() {
        HUDTool.showActivity()
        YSGMyopiaRecordViewModel.editMyopiaRecordDetail(recordId: recordId, checkInfo: viewModel?.toArray() ?? []) { (message, code) in
            HUDTool.hideActivity()
            switch code {
            case .failure:
                HUDTool.showError(message: message)
            case .success:
                HUDTool.show(message: "保存检查成功")
                self.navigationController?.popViewController(animated: true)
            }
        }
    }
}

extension YSGMyopiaRecordController: UITableViewDataSource {
    func numberOfSections(in tableView: UITableView) -> Int {
        return viewModel?.numberOfSection ?? 0
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return viewModel?.numberOfRow(in: section) ?? 0
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        switch indexPath.section {
        case 0:
            let cell = tableView.dequeueReusableCell(withIdentifier: YSGMyopiaRecordInfoCell.reuseIdentifier(),
                                                     for: indexPath) as! YSGMyopiaRecordInfoCell
            cell.configure(with: viewModel)
            return cell
        case 1:
            switch viewModel?.model.checkItemCode {
            case .eyePhoto, .eyePrevious:
                let cell = tableView.dequeueReusableCell(withIdentifier: YSGMyopiaRecordImageCell.reuseIdentifier(),
                                                         for: indexPath) as! YSGMyopiaRecordImageCell
                cell.delegate = self
                if let vm = viewModel {
                    cell.configure(with: vm, at: indexPath)
                }
                return cell
            case .eyePressure:
                let cell = tableView.dequeueReusableCell(withIdentifier: YSGMyopiaRecordEyePressureCell.reuseIdentifier(),
                                                         for: indexPath) as! YSGMyopiaRecordEyePressureCell
                cell.delegate = self
                if let vm = viewModel {
                    cell.configure(with: vm.checkInfoArr[indexPath.row], isEdited: vm.isEdited)
                }
                return cell
            case .eyeVision:
                let cell = tableView.dequeueReusableCell(withIdentifier: YSGMyopiaEyeVisionCell.reuseIdentifier(),
                                                         for: indexPath) as! YSGMyopiaEyeVisionCell
                cell.delegate = self
                if let vm = viewModel {
                    cell.configure(with: vm.checkInfoArr[indexPath.row], isEdited: vm.isEdited)
                }
                return cell
            case .eyeRefractive:
                let cell = tableView.dequeueReusableCell(withIdentifier: YSGMyopiaEyeDegreeCell.reuseIdentifier(),
                                                         for: indexPath) as! YSGMyopiaEyeDegreeCell
                cell.delegate = self
                if let vm = viewModel {
                    cell.configure(with: vm.checkInfoArr[indexPath.row], isEdited: vm.isEdited)
                }
                return cell
            default:
                return UITableViewCell()
            }
        case 2:
            let cell = tableView.dequeueReusableCell(withIdentifier: YSGMyopiaRecordImageCell.reuseIdentifier(),
                                                     for: indexPath) as! YSGMyopiaRecordImageCell
            cell.delegate = self
            if let vm = viewModel {
                cell.configure(with: vm, at: indexPath)
            }
            return cell
        default:
            return UITableViewCell()
        }
    }
}

extension YSGMyopiaRecordController: UITableViewDelegate {
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        switch indexPath.section {
        case 0: return UITableView.automaticDimension
        case 1: return viewModel?.cellHeight(at: indexPath) ?? 0
        case 2: return 185
        default: return 0
        }
    }
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        return nil
    }
    
    func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        switch viewModel?.model.checkItemCode {
        case .eyePressure:
            if section == 1 {
                let addFooter = UINib.loadViewFrom(YSGMyopiaEyePressureAddFooter.self)
                addFooter.frame = CGRect(x: 0, y: 0, width: screenW, height: 20)
                addFooter.hideUI(viewModel?.canAdd == false)
                addFooter.addHandle = { [weak self] in
                    guard let self = self else { return }
                    self.viewModel?.addCheckInfo()
                    self.tableView.reloadData()
                }
                return addFooter
            }
            return nil
        case .eyeVision, .eyeRefractive:
            return UIView()
        default:
            return nil
        }
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 0.0001
    }
    
    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        switch viewModel?.model.checkItemCode {
        case .eyePressure, .eyeVision, .eyeRefractive:
            return section == 1 ? 20 : 0.0001
        default:
            return 0.0001
        }
    }
}

extension YSGMyopiaRecordController: YSGMyopiaRecordImageCellDelegate, YSGMyopiaRecordCellDelegate {
    func recordImageCell(uploadImage cell: YSGMyopiaRecordImageCell) {
        showBottomAlert()
    }
    
    func recordImageCell(viewLargerImage cell: YSGMyopiaRecordImageCell) {
        let imagePicker = YSGImagePicker(currentImageView: cell.imgView)
        imagePicker.modalPresentationStyle = .custom
        present(imagePicker, animated: true, completion: nil)
    }
    
    func eyePressureCell(_ cell: YSGMyopiaRecordEyePressureCell, checkInfo: YSGMyopiaRecordDetailCheckInfo) {
        guard let indexPath = tableView.indexPath(for: cell) else { return }
        
        viewModel?.replaceCheckInfo(checkInfo, at: indexPath)
    }
    
    func eyeVisionCell(_ cell: YSGMyopiaEyeVisionCell, checkInfo: YSGMyopiaRecordDetailCheckInfo) {
        guard let indexPath = tableView.indexPath(for: cell) else { return }
        
        viewModel?.replaceCheckInfo(checkInfo, at: indexPath)
    }
    
    func eyeRefractiveCell(_ cell: YSGMyopiaEyeDegreeCell, checkInfo: YSGMyopiaRecordDetailCheckInfo) {
        guard let indexPath = tableView.indexPath(for: cell) else { return }
        
        viewModel?.replaceCheckInfo(checkInfo, at: indexPath)
    }
    
    func eyePressureCell(deleteHandle cell: YSGMyopiaRecordEyePressureCell) {
        guard let indexPath = tableView.indexPath(for: cell) else { return }
        
        viewModel?.removeCheckInfo(at: indexPath)
    }
}

// MARK: - UIImagePickerControllerDelegate
extension YSGMyopiaRecordController: UIImagePickerControllerDelegate, UINavigationControllerDelegate {
    private func showBottomAlert() {
        let alert = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet)

        let cancel = UIAlertAction(title:"取消", style: .cancel, handler: nil)
        let takingPictures = UIAlertAction(title:"拍照", style: .default) {
            action in
            self.goCamera()
            
        }
        let localPhoto = UIAlertAction(title:"从手机相册选择", style: .default) {
            action in
            self.goImage()
            
        }
        alert.addAction(cancel)
        alert.addAction(takingPictures)
        alert.addAction(localPhoto)
        present(alert, animated:true, completion:nil)
        
    }
    
    private func goCamera() {
        if UIImagePickerController.isSourceTypeAvailable(.camera) {
            let cameraPicker = UIImagePickerController()
            cameraPicker.delegate = self
            cameraPicker.sourceType = .camera
            present(cameraPicker, animated: true, completion: nil)
        } else {
            HUDTool.show(message: "相机权限未打开!")
        }
    }
    
    private func goImage() {
        let photoPicker =  UIImagePickerController()
        photoPicker.delegate = self
        photoPicker.sourceType = .photoLibrary
        present(photoPicker, animated: true, completion: nil)
    }
    
    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
        if let image = info[UIImagePickerController.InfoKey.originalImage] as? UIImage {

            YSGImageUpload.upload(image: image, imageType: viewModel?.model.checkItemCode?.imageType ?? .eyePressure) { code, model, error in
                switch code {
                case .success:
                    self.viewModel?.model.url = model?.shareUrl
                case .failure:
                    HUDTool.showError(message: error)
                }
            }
        }
        dismiss(animated: true, completion: nil)
    }
}
